﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace DnD.Model
{
    class DnDRestService
    {

        private string serviceURL = "http://192.168.0.101:8080/com.mud.dnd.frontend.rs";


        public async void loginUser(string name, string password, Func<String, String> resultHandler)
        {
            String request = "/User/login?name=" + name + "&pass=" + password;

            var serviceClient = new HttpClient();
            try
            {

                var result = await serviceClient.GetStringAsync(serviceURL + request);
                string[] resultArray = result.Split(new Char[] { ':' });

                if (resultArray.Length > 1 && resultArray[0] != "ERROR")
                {
                    resultHandler(resultArray[1]);
                }
                else
                {
                    resultHandler("ERROR");
                }
            }
            catch (Exception error)
            {
                resultHandler("ERROR");
            }

                // cardList = dowloadedCards;
            
            
        }



        



        public async void queryCards(String name, String desc, String userName, int rating, int deckID, ObservableCollection<Card> cardList)
        {
            String request = "/Card/query?";

            if (name != "")
            {
                request += "name=" + name + "&";
            }
            if (desc != "")
            {
                request += "desc=" + desc + "&";
            }
            if (userName != "")
            {
                request += "userName=" + userName + "&";
            }
            if (rating!= 0)
            {
                request += "rate=" + rating + "&rateOp=more&";
            }
            if (deckID != 0)
            {
                request += "deckID=" + deckID + "&";
            }

            var serviceClient = new HttpClient();


            try
            {

                var result = await serviceClient.GetStringAsync(serviceURL + request);
                //JObject jsonObject = JObject.Parse(@"{""cardlist"":"+result+"}");
                //JArray jsonCardList = (JArray)jsonObject["cardlist"];
                JArray jsonCardList = JArray.Parse(result);

                ObservableCollection<Card> dowloadedCards = new ObservableCollection<Card>();

                foreach(JObject jsonCard in jsonCardList)
                {
                    Card newCard = new Card(((string)jsonCard["name"]), ((string)jsonCard["description"]), ((string)jsonCard["pictureURL"]), ((string)jsonCard["type"]), ((int)jsonCard["rarity"]));
                    newCard.Rate = ((int)jsonCard["rate"]);
                    newCard.OnlineID = ((int)jsonCard["id"]);
                    newCard.Author = ((string)((JObject)jsonCard["author"])["name"]);
                    cardList.Add(newCard);
                }


               // cardList = dowloadedCards;
            }
            catch (Exception e)
            {
                //Debug.WriteLine(e.ToString());
            }

           
        }


        public async void deleteCard(int cardID, string userName, string sessionID,Func<bool, String> resultHandler)
        {
            String request = "/Card/delete?id=" + cardID+"&userName="+userName+"&sessionID="+sessionID;

            var serviceClient = new HttpClient();
            try
            {

                var result = await serviceClient.GetStringAsync(serviceURL + request);


                if (result == "OK")
                {
                    resultHandler(true);
                }
                else
                {
                    resultHandler(false);
                }
            }
            catch (Exception error)
            {
                resultHandler(false);
            }

            // cardList = dowloadedCards;


        }


        public async void updateCard(int cardID, String name, String desc, string userName, string sessionID, Func<bool, String> resultHandler)
        {
            String request = "/Card/update?";

            if (name != "")
            {
                request += "name=" + name + "&";
            }
            if (desc != "")
            {
                request += "desc=" + desc + "&";
            }
           
            request +="id="+cardID.ToString()+"&userName=" + userName + "&sessionID="+sessionID;
            
            

            var serviceClient = new HttpClient();
            try
            {

                var result = await serviceClient.GetStringAsync(serviceURL + request);
                if (result == "OK")
                {
                    resultHandler(true);
                }
                else
                {
                    resultHandler(false);
                }
            }
            catch (Exception error)
            {
                resultHandler(false);
            }


        }

        async public Task<HttpResponseMessage> UploadImage(byte[] ImageData, int onlineID ,string userName, string sessionID)
        {

            string request = "/GameItem/Picture/uploadPic?";
            request +="&gameItemID="+ onlineID +"&userName=" + userName + "&sessionID=" + sessionID;

            var serviceClient = new HttpClient();
            var requestContent = new MultipartFormDataContent();
            //    here you can specify boundary if you need---^
            var imageContent = new ByteArrayContent(ImageData);
            imageContent.Headers.ContentType =
                MediaTypeHeaderValue.Parse("image/jpeg");

            requestContent.Add(imageContent, "image", "image.jpg");

            return await serviceClient.PostAsync(serviceURL + request, requestContent);
        }

    }
}
